# -*- coding: utf-8 -*-
import xbmc
import threading

m3u8_file = None

class MyPlayer(xbmc.Player):
    def __init__(self):
        self.vid = None
        self.rollback = 3
        self.playlist = None
        xbmc.Player.__init__(self)

    def play(self, item='', listitem=None, windowed=False, startpos=-1, arg=None):
        self.playlist = item

        self.vid = arg
        offset = 0
        startpos = 0
        self.base = 0
        self.last = 0
        self.lastpos = 0
        if item[0].getfilename() == m3u8_file:
            self.isM3U8 = True
        else:
            self.isM3U8 = False

        if offset > 0:
            item[startpos].setProperty('StartOffset', str(offset))

        t = threading.Timer(1, self.timeEntry)
        t.start()

        try:
            xbmc.Player.play(self, item, listitem, windowed, startpos)
        except:
            xbmc.Player.play(self, item, listitem, windowed)

    def getPlaylist(self):
        # if self.playlist == None:
        self.playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
        return self.playlist

    def timeEntry(self):
        self.updateHistory()
        try:
            if self.isPlaying():
                t = threading.Timer(1, self.timeEntry)
                t.start()
        except:
            pass

    def onPlayBackStarted(self):
        self.updateHistory(False)
        xbmc.Player.onPlayBackStarted(self)

    def onPlayBackSeek(self, time, seekOffset):
        self.updateHistory(False, time / 1000)
        xbmc.Player.onPlayBackSeek(self, time, seekOffset)

    def onPlayBackSeekChapter(self, chapter):
        self.updateHistory(False)
        xbmc.Player.onPlayBackSeek(self, chapter)

    def onPlayBackEnded(self):
        xbmc.Player.onPlayBackEnded(self)

    def onPlayBackStopped(self):
        pass
        # cache.set(self.vid, repr({'offset':self.last, 'startpos':self.lastpos}))

    def updateHistory(self, check=True, base=-1):
        pass
        # if self.isPlaying() == True:
        #     if check == True and self.isM3U8 == True:
        #         offset = self.getTime()
        #         if (offset > self.base) and (offset < self.base + 1.5):
        #             self.last += offset - self.base
        #         self.base = offset
        #     elif base == -1 or self.isM3U8 == False:
        #         self.last = self.getTime()
        #         self.base = self.last
        #     else:
        #         self.last = base
        #         self.base = base
        #
        #     self.lastpos = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()


player = MyPlayer()